package it.mp.multitask.preference;

import it.mp.multitask.R;

import java.io.File;
import java.io.FilenameFilter;
import android.content.Context;
import android.net.Uri;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

public class GalleryPreference extends android.preference.Preference {

	private Gallery ig;
	private Uri[] mUrls;
	private final int[] mIDBackground=new int[]{R.drawable.scrivania1,R.drawable.scrivania2,R.drawable.scrivania3,R.drawable.scrivania4,R.drawable.scrivania5,R.drawable.scrivania6,R.drawable.scrivania7};
	String[] mFiles = null;

	public GalleryPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	@Override
	protected View onCreateView(ViewGroup parent) {

		File images = new File("/sdcard/mtm");
		File[] imagelist = images.listFiles(new FilenameFilter() {

			public boolean accept(File dir, String name) {
				return ((name.endsWith(".jpg")) || (name.endsWith(".png")));
			}
		});
		mFiles = new String[imagelist.length];
		for (int i = 0; i < imagelist.length; i++) {
			mFiles[i] = imagelist[i].getAbsolutePath();
		}		
		mUrls = new Uri[mFiles.length];
		for (int i = 0; i < mFiles.length; i++) {
			mUrls[i] = Uri.parse(mFiles[i]);
		}

		ig = new Gallery(getContext());
		ig.setAdapter(new ImageAdapter(this.getContext()));
		ig.setFadingEdgeLength(40);
		ig.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int posizione, long arg3) {
				if (posizione>mUrls.length-1){
					GalleryPreference.this.persistString(String.valueOf(mIDBackground[posizione-mUrls.length]));
				}else{
					GalleryPreference.this.persistString(mUrls[posizione].toString());					
				}
			}
		});
		return ig;
	}
	public class ImageAdapter extends BaseAdapter {
		int mGalleryItemBackground;
		private Context mContext;

		public ImageAdapter(Context c) {
			mContext = c;
		}
		public int getCount() {
			return mUrls.length+mIDBackground.length;
		}
		public Object getItem(int position) {
			return position;
		}
		public long getItemId(int position) {
			return position;
		}
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView i = new ImageView(mContext);

			if (position>mUrls.length-1){
				i.setImageResource(mIDBackground[position-mUrls.length]);
			}else{
				i.setImageURI(mUrls[position]);
			}
			i.setScaleType(ImageView.ScaleType.FIT_XY);
			i.setLayoutParams(new Gallery.LayoutParams(150, 100));
			return i;
		}
	}
}
